//
//  ZNSlideView.m
//  AiShangCity
//
//  Created by 李振宁 on 9/16/15.
//  Copyright (c) 2015 LiZhenning. All rights reserved.
//

#import "ZNSlideView.h"

@interface ZNSlideView ()
<
UIScrollViewDelegate
>
{
    BOOL isScrolling;
    NSMutableArray *arrayImages;
    UIImageView *imageFirst;
    UIImageView *imageLast;
    UIImageView * bgImageTitle;
    
}
@end

@implementation ZNSlideView

@synthesize dataSource = _dataSource;
@synthesize delegate = _delegate;
@synthesize scrollView = _scrollView;
@synthesize pageControl = _pageControl;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    
    if (self)
    {
        isScrolling = NO;
        
        arrayImages = [[NSMutableArray alloc] initWithCapacity:0];
        
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        [_scrollView setDelegate:self];
        [_scrollView setShowsHorizontalScrollIndicator:NO];
        [_scrollView setShowsVerticalScrollIndicator:NO];
        [_scrollView setPagingEnabled:YES];
        [self addSubview:_scrollView];
        
    

        _pageControl = [[UIPageControl alloc] init];
        _pageControl.currentPageIndicatorTintColor = [UIColor redColor];
        _pageControl.pageIndicatorTintColor = [UIColor whiteColor];
        [_pageControl setFrame:CGRectMake(0, frame.size.height - 40, 100 * kAutoScanleX, 40)];
        [self addSubview:_pageControl];
        
        
        bgImageTitle = [[UIImageView alloc]initWithFrame:CGRectMake(0, frame.size.height - 40, frame.size.width, 40)];
        [bgImageTitle setHidden:YES];
        [self addSubview:bgImageTitle];
        [bgImageTitle setImage:[UIImage imageNamed:@"bg_lunbo_biaoti"]];
       

        
        _labelTitle = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, frame.size.width-30, 40)];
        [_labelTitle setTextColor:[UIColor whiteColor]];
        [_labelTitle setBackgroundColor:[UIColor clearColor]];
        [_labelTitle setFont:[UIFont systemFontOfSize:14]];
        [bgImageTitle addSubview:_labelTitle];
        
        
    }
    
    return self;
}

- (void)setDataSource:(id<ZNSlideViewDataSource>)dataSource
{
    _dataSource = dataSource;
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    isScrolling = YES;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSInteger x = scrollView.contentOffset.x / scrollView.frame.size.width;
    NSInteger count = scrollView.contentSize.width / scrollView.frame.size.width;
    NSInteger page = x;
    
    if (x == 0)
    {
        page = count - 2;
    }
    
    if (x == (count - 1))
    {
        page = 1;
    }
    
    page = page - 1;
    
    
    [_pageControl setCurrentPage:page];
    
    if (_delegate && [_delegate respondsToSelector:@selector(slideView:itemForPosition:)])
    {
        [_delegate slide:self DidMoveToPosition:page];
    }
    
  
    
}


- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    
    
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    
    isScrolling = NO;
    
    NSInteger x = scrollView.contentOffset.x / scrollView.frame.size.width;
    NSInteger count = scrollView.contentSize.width / scrollView.frame.size.width;
    
    if (x == 0)
    {
        [scrollView setContentOffset:CGPointMake((count - 2) * scrollView.frame.size.width, 0)];
        
    }
    
    if (x == (count - 1))
    {
        [scrollView setContentOffset:CGPointMake(1 * scrollView.frame.size.width, 0)];
    }
    
    
    NSInteger page = x;
    
    if (x == 0)
    {
        page = count - 2;
    }
    
    if (x == (count - 1))
    {
        page = 1;
    }
    
    page = page - 1;
    
    
    [self setupImagePage:page];
    [self setupImageTitle:page];
    
}

- (void)setupImageTitle:(NSInteger)page{
    
    if ([self.dataSource respondsToSelector:@selector(slideItemImageTitleForPosition:)]) {
       
        [bgImageTitle setHidden:NO];
        _labelTitle.text = [_dataSource slideItemImageTitleForPosition:page];
    }
    
}


- (void)setupImagePage:(NSInteger)page {
    
    UIView *view = arrayImages[page];
    UIImageView *imageView = [view viewWithTag:999];
    NSString *string = [_dataSource slideItemImageURLForPosition:page];
    
    NSURL *url = [NSURL URLWithString:string];
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
    __block UIImage *img;
    
    [manager diskImageExistsForURL:url completion:^(BOOL isInCache) {
        
        if (isInCache) {
            
            img =[[manager imageCache] imageFromDiskCacheForKey:url.absoluteString];
            [imageView setImage:img];
            
        }else{
            
             UIImage *imageDefault = [_dataSource slideDefaultImage];
            [imageView sd_setImageWithURL:[NSURL URLWithString:string] placeholderImage:imageDefault];
        }
        
    }];
    
    
    NSInteger count = [_dataSource countOfSlideView:self];
    
    if (page == 0)
    {
       [imageLast sd_setImageWithURL:[NSURL URLWithString:string]];
    }
    
    
    if (page == count - 1)
    {
        [imageFirst sd_setImageWithURL:[NSURL URLWithString:string]];
    }
    
}

- (void)reload
{
    [arrayImages removeAllObjects];
    
    for (UIView *view in _scrollView.subviews)
    {
        [view removeFromSuperview];
    }
    
    [self timerStop];
    
    [self initScrollContainer];
}

- (void)initScrollContainer
{
    
    NSInteger count = [_dataSource countOfSlideView:self];
    UIImage *imageDefault = [_dataSource slideDefaultImage];
    
    if (count == 0)
    {
        [_pageControl setNumberOfPages:0];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, _scrollView.frame.size.width, _scrollView.frame.size.height)];
        [imageView setImage:imageDefault];
        [_scrollView addSubview:imageView];
        
        [_scrollView setContentSize:CGSizeMake(_scrollView.frame.size.width, _scrollView.frame.size.height)];
        
        [_scrollView setContentOffset:CGPointMake(0, 0)];
        
    }else
    {
        [_pageControl setNumberOfPages:count];
        [_pageControl setCurrentPage:0];
        
        //左侧
        
        UIView *view1 = [_dataSource slideView:self itemForPosition:(count - 1)];
        [view1 setFrame:CGRectMake(0, 0, _scrollView.frame.size.width, _scrollView.frame.size.height)];
        [_scrollView addSubview:view1];
        
        imageFirst = [view1 viewWithTag:999];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setFrame:CGRectMake(0, 0, _scrollView.frame.size.width, _scrollView.frame.size.height)];
        [button addTarget:self action:@selector(btnItemPressed:) forControlEvents:UIControlEventTouchUpInside];
        [button setTag:(count - 1)];
        [_scrollView addSubview:button];
        
        for (NSInteger i = 0 ; i < count ; i ++)
        {
            NSInteger xOffset = i + 1;
            
            UIView *view = [_dataSource slideView:self itemForPosition:i];
            [view setFrame:CGRectMake(_scrollView.frame.size.width * xOffset, 0, _scrollView.frame.size.width, _scrollView.frame.size.height)];
            [_scrollView addSubview:view];
            
            [arrayImages addObject:view];
            
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setFrame:CGRectMake(_scrollView.frame.size.width * xOffset, 0, _scrollView.frame.size.width, _scrollView.frame.size.height)];
            [button addTarget:self action:@selector(btnItemPressed:) forControlEvents:UIControlEventTouchUpInside];
            [button setTag:i];
            [_scrollView addSubview:button];
            
        }
        
        
        //右侧
        view1 = [_dataSource slideView:self itemForPosition:0];
        [view1 setFrame:CGRectMake(_scrollView.frame.size.width * (count + 1), 0, _scrollView.frame.size.width, _scrollView.frame.size.height)];
        [_scrollView addSubview:view1];
        
        imageLast = [view1 viewWithTag:999];
        
        button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setFrame:CGRectMake(_scrollView.frame.size.width * (count + 1), 0, _scrollView.frame.size.width, _scrollView.frame.size.height)];
        [button addTarget:self action:@selector(btnItemPressed:) forControlEvents:UIControlEventTouchUpInside];
        [button setTag:0];
        [_scrollView addSubview:button];
        
        
        [_scrollView setContentSize:CGSizeMake(_scrollView.frame.size.width * (count + 2), _scrollView.frame.size.height)];
        
        [_scrollView setContentOffset:CGPointMake(_scrollView.frame.size.width, 0)];
        
        if (count == 1)
        {
            [_scrollView setScrollEnabled:NO];
            [self timerStop];
            
        }else
        {
            [_scrollView setScrollEnabled:YES];
            [self performSelector:@selector(timerStart) withObject:nil afterDelay:1];
        }
        
        if (count != 0)
        {
            [self setupImagePage:0];
            [self setupImageTitle:0];
        }
    }
}

- (void)btnItemPressed:(id)sender
{
    
   
     UIButton *btn = (UIButton *)sender;
    
    if ([_delegate respondsToSelector:@selector(slideViewSelected:)])
    {
        [_delegate slideViewSelected:btn.tag];
    }
}

- (void)timerStart
{
    [self timerStop];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(timerDo) userInfo:nil repeats:YES];
}

- (void)timerStop
{
    if (_timer != nil)
    {
        [_timer invalidate];
        _timer = nil;
    }
}

- (void)timerDo
{
    if (isScrolling)
    {
        return;
    }
    
    NSInteger x = _scrollView.contentOffset.x / _scrollView.frame.size.width;
    NSInteger count = _scrollView.contentSize.width / _scrollView.frame.size.width;
    
    NSInteger page = x;
    
    if (x == (count - 2))
    {
        [_scrollView setContentOffset:CGPointMake(0, 0)];
        
        page = 0;
    }
    
    page = page + 1;
    
    [self setupImagePage:page-1];
    [self setupImageTitle:page-1];
    
    [_scrollView setContentOffset:CGPointMake(page * _scrollView.frame.size.width, 0) animated:YES];
}
- (void)willMoveToSuperview:(UIView *)newSuperview
{
    [super willMoveToSuperview:newSuperview];
    
    if (newSuperview == nil)
    {
        return;
    }
    
    //view 开始加载在superview时的处理方法
    
    [self initScrollContainer];
    
}

- (void)didMoveToSuperview
{
    [super didMoveToSuperview];
    
}

@end
